﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using FingerPrint.WebUI.Abstract;
using FingerPrint.WebUI.Models;

namespace FingerPrint.WebUI.Controllers
{
    [Authorize]             //Authorization is defined in controller
    public class AdminController : Controller
    {
        private ISalesOrderRepository repository;
        public AdminController(ISalesOrderRepository repo)
        {
            repository = repo;

        }

        public ViewResult Index()
        {
            return View(repository.SalesOrders);
        }

        public ViewResult Create()
        {
            return View("Edit", new SalesOrder());
        }

        public ViewResult Edit(int salesOrderID)
        {
            SalesOrder salesOrder = repository.SalesOrders.FirstOrDefault(s => s.SalesOrderID == salesOrderID);
            return View(salesOrder);
        }


        [HttpPost]
        public ActionResult Edit(SalesOrder salesOrder)
        {
            if (ModelState.IsValid)
            {
                repository.SaveSalesOrder(salesOrder);
                TempData["message"] = string.Format("{0} has been saved", salesOrder.SalesOrderID);
                return RedirectToAction("Index");
            }
            else
            {
                // there is something wrong with the data values
                return View(salesOrder);
            }
        }

        [HttpPost]
        public ActionResult Delete(int salesOrderID)
        {
            SalesOrder salesOrder = repository.SalesOrders.FirstOrDefault(s => s.SalesOrderID == salesOrderID);
            if (salesOrder != null)
            {
                repository.DeleteSalesOrder(salesOrder);
                TempData["message"] = string.Format("{0} was deleted", salesOrder.SalesOrderID);
            }

            return RedirectToAction("Index");

        }
    }
}
